﻿'use strict';
const fs = require('fs');
const path = require('path');
const XLSX = require('xlsx');

String.prototype.replaceAll = function (search, replacement) {
	return this.replace(new RegExp(search, 'g'), replacement);
};

const FILE_OBJECT_TEMP = `
import { _decorator, Node, __private} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('%fileName%')
export class %fileName%{
%defineTxt%
}
`


const FILE_DATA_TEMP = `
import { _decorator, Node, __private} from 'cc';
import { %fileObjectName% } from './%fileObjectName%';
const { ccclass, property } = _decorator;

@ccclass('%fileName%')
export class %fileName%{
	static data: Map<number, %fileObjectName%> = new Map([
%dataTxt%
	])
}

`
const FILE_PY_TEMP = `
# coding=utf-8
from typing import Dict, Any


class %fileObjectName%:
%defineTxt%

	def __init__(self, *args, **kwargs):
		for key, value in kwargs.items():
			setattr(self, key, value)

data: Dict[int, %fileObjectName%] = {
%dataTxt%
}

`



var startI = 4;
var startJ = 4;

var excelPath = "";
var dataPath = "";
var serverDataPath = "";

const capitalizeFirstLetter = function (str) {
	// 检查字符串是否为空
	if (str.length === 0) return str;

	// 将第一个字母转换为大写，并与剩余部分拼接
	return str.charAt(0).toUpperCase() + str.slice(1);
}

const writeData = function (fileName, typeList, fieldList, worksheet, maxI, maxJ) {

	let fileObjectName = capitalizeFirstLetter(fileName) + "DataObject"
	fileName = capitalizeFirstLetter(fileName) + "Data"
	
	let txt = FILE_DATA_TEMP
	txt = txt.replaceAll("%fileName%", fileName)
	txt = txt.replaceAll("%fileObjectName%", fileObjectName)
	let dataTxt = ""

	for (let i = startI + 2; i < maxI; i++) {
		let num = readCell(worksheet, i, startJ)
		let txt = "\t\t[" + num + ", {\n";
		for (let j = startJ; j < maxJ; j++) {
			let data = readCell(worksheet, i, j)
			let typeName = typeList[j - startJ]
			let fieldName = fieldList[j - startJ]


			if (typeName == "string") {
				data = "'" + data + "'";
			}

			txt += "\t\t\t" + fieldName + ": " + data + ",\n";
		}
		txt += "\t\t}],\n";
		dataTxt += txt;
	}

	txt = txt.replaceAll("%dataTxt%", dataTxt)

	writeFile(dataPath + fileName + ".ts", txt)

};


const writeDataObject = function (fileName, typeList, fieldList) {
	fileName = capitalizeFirstLetter(fileName) + "DataObject"
	let txt = FILE_OBJECT_TEMP
	txt = txt.replaceAll("%fileName%", fileName)
	let defineTxt = ""
	for (let i = 0; i < typeList.length; i++) {
		let typeName = typeList[i]
		if (typeName == "other") {
			typeName="any"
		}

		defineTxt += "\t" + fieldList[i] + ": " + typeName +";\n"
	}
	txt = txt.replaceAll("%defineTxt%", defineTxt)
	writeFile(dataPath + fileName+".ts", txt)

};

const writePyData = function (fileName, typeList, fieldList, worksheet, maxI, maxJ) {

	let fileObjectName = capitalizeFirstLetter(fileName) + "DataObject"
	fileName = capitalizeFirstLetter(fileName) + "Data"

	let txt = FILE_PY_TEMP
	txt = txt.replaceAll("%fileObjectName%", fileObjectName)


	let defineTxt = ""
	for (let i = 0; i < typeList.length; i++) {
		let typeName = typeList[i]
		if (typeName == "other") {
			typeName = "Any"
		} else if (typeName == "string") {
			typeName = "str"
		} else if (typeName == "number") {
			typeName = "int"
		} else if (typeName == "boolean") {
			typeName = "bool"
		}

		defineTxt += "\t" + fieldList[i] + ": " + typeName + "\n"
	}
	txt = txt.replaceAll("%defineTxt%", defineTxt)





	let dataTxt = ""

	for (let i = startI + 2; i < maxI; i++) {
		let num = readCell(worksheet, i, startJ)
		let txt = "\t" + num + ": " + fileObjectName+"(\n";
		for (let j = startJ; j < maxJ; j++) {
			let data = readCell(worksheet, i, j)
			let typeName = typeList[j - startJ]
			let fieldName = fieldList[j - startJ]


			if (typeName == "string") {
				data = "'" + data + "'";
			} else if (typeName == "boolean") {
				if (data == "true") {
					data = "True";
				} else {
					data = "False";
				}
			}


			txt += "\t\t" + fieldName + "=" + data + ",\n";
		}
		txt += "\t),\n";
		dataTxt += txt;
	}

	txt = txt.replaceAll("%dataTxt%", dataTxt)

	writeFile(serverDataPath + fileName + ".py", txt)

};


const writeFile = async function (savePath, txt) {
	fs.writeFile(savePath, '\uFEFF' + txt, { encoding: 'utf8' }, (err) => {
		if (err) {
			console.error("保存文件失败=" + err);
		} else {
			console.log("导出excel成功");
		}
	});
};
const readCell = function (worksheet, i, j) {
	const cellAddress = XLSX.utils.encode_cell({ r: i, c: j });


	const cellData = worksheet[cellAddress];
	if (cellData == null)
		return "";
	return cellData.v
};

const exportExcel = function (filePath) {
	const workbook = XLSX.readFile(filePath);

	// 去掉扩展名，只获取文件名
	const fileName = path.basename(filePath, path.extname(filePath));

	// 获取第一个工作表
	const sheetName = workbook.SheetNames[0];
	const worksheet = workbook.Sheets[sheetName];

	let maxI = startI;
	let maxJ = startJ;
	for (let i = startI; i < 1000; i++) {
		let data = readCell(worksheet, i, startJ)
		if (data == "" || data == null) {
			maxI = i;
			break;
		}
	}

	for (let j = startJ; j < 1000; j++) {
		let data = readCell(worksheet, startI, j)
		if (data == "" || data == null) {
			maxJ = j;
			break;
		}
	}

	let typeList = []
	for (let j = startJ; j < maxJ; j++) {
		typeList.push(readCell(worksheet, startI, j))
	}
	let fieldList = []
	for (let j = startJ; j < maxJ; j++) {
		fieldList.push(readCell(worksheet, startI+1, j))
	}
	writeDataObject(fileName, typeList, fieldList)
	writeData(fileName, typeList, fieldList, worksheet, maxI, maxJ)
	writePyData(fileName, typeList, fieldList, worksheet, maxI, maxJ)
}

// 获取指定路径下所有 Excel 文件的完整路径
const getExcelFiles = function (directoryPath) {
	// 读取指定目录下的所有文件
	const files = fs.readdirSync(directoryPath);

	// 筛选出所有 Excel 文件（以 .xlsx 或 .xls 结尾）
	const excelFiles = files.filter(file => {
		return (file.endsWith('.xlsx') || file.endsWith('.xls')) && file.indexOf("~$")==-1;
	}).map(file => path.join(directoryPath, file));  // 获取文件的完整路径

	return excelFiles;
}


module.exports = {

	load() {
		// 当 package 被正确加载的时候执行
		let dirPath = path.resolve(__dirname + "/../../")
		excelPath = path.join(dirPath, "../excel/")
		dataPath = path.join(dirPath, "./assets/script/data/")
		serverDataPath = path.join(dirPath, "../ku-server/src/data/")
	},

	unload() {
		// 当 package 被正确卸载的时候执行
	},

	methods: {
		async createExcelCode() {
			let excelFiles = getExcelFiles(excelPath)
			for (let filePath of excelFiles) {
				exportExcel(filePath)
			}
		
		},

	}
};
